<!--
 * @Description: 项目台账，总模块，集成增删查改
 * @Author: youzi
 * @Date: 2020-05-25 11:18:02
 * @LastEditors: youzi
 * @LastEditTime: 2020-08-28 17:37:57
-->
<template>
  <div style="width: 100%;" class="card-area">
    <layout-content topTitle="查询" bottomTitle="会员管理">
      <!-- 搜索区域 -->
      <template v-slot:topCard>
        <search-view ref="searchView" @search="search"></search-view>
      </template>
      <!-- 额外操作，在右侧 -->
      <template v-slot:extraOperation>
        <!-- <a-button class="extra-btn" v-hasPermission="'role:add'" type="primary" @click="addVisible = true">
          新增
        </a-button> -->
      </template>
      <!-- 表格区域 -->
      <template v-slot:bottomCard>
        <a-table
          ref="TableInfo"
          :columns="columns"
          rowKey="id"
          :dataSource="dataSource"
          :pagination="pagination"
          :loading="loading"
          :scroll="{ x: 900 }"
          @change="handleTableChange"
        >
          <template slot="ssex" slot-scope="text">
            <span>{{ ssexMap[text] || '--' }}</span>
          </template>
          <template slot="status" slot-scope="text">
            <span>{{ statusMap[text] }}</span>
          </template>
          <template slot="operation" slot-scope="text, record">
            <a-button type="link" @click="info(record)" class="icon">详情</a-button>
            <!-- <a-button
              v-hasPermission="'role:update'"
              type="link"
              @click="edit(record)"
              class="icon"
              style="padding-left:10px"
              >修改
            </a-button> -->
            <!-- <a-button
              v-if="record.status === 1"
              v-hasPermission="'role:delete'"
              type="link"
              class="icon"
              style="padding-left:10px"
              @click="onApproval(record.id, 2)"
              >提交
            </a-button> --> 
            <a-button
              v-hasPermission="'role:delete'"
              type="link"
              @click="onDelete(record)"
              class="icon"
              style="padding-left:10px"
              >禁用
            </a-button>
          </template>
        </a-table>
        <!-- 查看 -->
        <info-record :visible="infoVisible" @close="infoVisible = false" :initRecord="selectedRecord" :apiURL="apiURL">
        </info-record>
        <!-- 新增 -->
        <!-- <add-record
          :visible="addVisible"
          :modelTreeOptions="modelTreeOptions"
          @close="addVisible = false"
          @success="onAddSuccess"
          :apiURL="apiURL"
        ></add-record> -->
        <!-- 修改 -->
        <!-- <edit-record
          :modelTreeOptions="modelTreeOptions"
          :visible="editVisible"
          ref="exactEdit"
          :initRecord="selectedRecord"
          @close="editVisible = false"
          @success="onEditSuccess"
          :apiURL="apiURL"
        >
        </edit-record> -->
      </template>
    </layout-content>
  </div>
</template>

<script>
import db from 'utils/localstorage';
import columns from './columns';
import apiURL from './requestURL';
import searchView from './search-view';
// import addRecord from './add';
// import editRecord from './edit';
import infoRecord from './info';
import layoutContent from '@/components/tool/layout-content';

export default {
  name: 'mainPage',
  components: { searchView, infoRecord, layoutContent },
  data() {
    return {
      params: {},
      columns, // 表头字段
      apiURL, // 接口url
      users: [], // 用户列表
      // 组件的可见性
      addVisible: false,
      editVisible: false,
      infoVisible: false,
      // 当前选中的记录
      selectedRecord: {},
      dataSource: [],
      sortedInfo: null,
      paginationInfo: null,
      pagination: {
        size: 'small',
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      statusMap: Object.freeze({
        '0': '有效',
        '1': '系统锁定2',
        '2': '禁用'
      }),
      ssexMap: Object.freeze({
        '1': '男',
        '2': '女',
        '3': '保密'
      }),
      modelTree: [] // 车型
    };
  },
  computed: {
    modelTreeMap () {
      const temp = {}
      const flat = (arr) => {
        arr.forEach(item => {
          if (item.childCarModels && item.childCarModels.length) {
            flat(item.childCarModels)
          }
          if (item.id) {
            temp[item.id] = item
          }
        })
      }
      flat(this.modelTree)
      return temp
    },
    modelTreeOptions () {
      return Object.keys(this.modelTreeMap || {}).map(key => {
        const item = this.modelTreeMap[key]
        return {
          label: item.model,
          value: item.id,
          key: item.id
        }
      })
    }
  },
  created() {
  },
  mounted() {
    this.fetch();
  },
  methods: {
    // ------------------------- 界面交互事件 -------------------------
    // 新增记录成功的回调
    onAddSuccess() {
      this.addVisible = false;
      this.$message.success('新增记录成功');
      this.search(this.params);
    },
    // 查看记录详情
    info(record) {
      this.selectedRecord = record;
      this.infoVisible = true;
    },
    // 修改记录
    edit(record) {
      for (var i = 0; i < this.users.length; i++) {
        let user = this.users[i];
        if (record.operatorName == user.username) {
          record.operatorId = user.userId;
        }
      }
      this.selectedRecord = record;
      this.editVisible = true;
    },
    // 修改记录成功的回调
    onEditSuccess(msg = '修改记录成功') {
      this.editVisible = false;
      this.$message.success(msg);
      this.search(this.params);
    },
    // 删除记录
    onDelete(record) {
      let that = this;
      this.$confirm({
        title: '确定禁用吗?',
        content: '禁用将不能登录哦！',
        centered: true,
        onOk() {
          that.$post(apiURL.deleteRecord, { usercode: record.usercode, stat : 2 }).then(() => {
            that.$message.success('删除成功');
            that.search(that.params);
          });
        },
        onCancel() {}
      });
    }, 
    // 分页信息改变时的回调
    handleTableChange(pagination, filters, sorter) {
      // 将这两个参数赋值给Vue data，用于后续使用
      this.paginationInfo = pagination;
      this.sortedInfo = sorter;
      this.fetch({
        ...this.params,
        sortField: sorter.field,
        sortOrder: sorter.order
      });
    },
    // 搜索
    search(params = {}) {
      this.params = params;
      let { sortedInfo } = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        ...params,
        sortField: sortField,
        sortOrder: sortOrder
      });
    },

    // ------------------------- 网络请求 -------------------------
    // 1.查询记录
    fetch(params = {}) {
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.count = this.pagination.defaultPageSize;
        params.currentPage = this.pagination.defaultCurrent;
      }
      params.userType = 1;
      console.log(params);
      this.$get(apiURL.getRecords, {
        ...params
      }).then(r => {
        console.log(r);
        let data = r.data.data;
        let pagination = { ...this.pagination };
        pagination.total = data.total;
        this.dataSource = data.rows;
        this.pagination = pagination;
        this.loading = false;
      }).catch(e => {
        console.error(e);
        this.loading = false;
      });
    },
  }
};
</script>

<style lang="less" scoped>
.icon {
  padding: 0;
  border: none;
  color: #1890ff;
}
.card-area {
  .extra-btn {
    width: 86px;
  }
}
.search-btn {
  margin-top: 8px;
}
.border-span {
  width: 2px;
  background-color: #cfd7de;
  height: 16px;
  margin-right: 2px;
  display: inline-block;
}
</style>
